package com.zx.zxblog.controller;

import com.zx.zxblog.entity.pojo.Blog;
import com.zx.zxblog.mapper.BlogMapper;
import com.zx.zxblog.service.BlogService;
import com.zx.zxblog.util.R;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

/**
 * className=IndexController
 * package=com.zx.zxblog.controller
 * description:
 *
 * @Author:SKEZhi
 * @Create:2024/4/4 - 14:02
 * @Version: v1.0
 */
@Controller
public class IndexController {
    @Autowired
    private BlogMapper blogMapper;

    @Autowired
    private BlogService blogService;
    @GetMapping(value = {"/",})
    public String index(Model model){
        List<Blog> blogList = blogMapper.selectList(null);
        Blog firstBlog = blogList.get(0);
        Blog secondBlog = blogList.get(1);
        Blog thirdBlog = blogList.get(2);
        model.addAttribute("blogTitle", firstBlog.getTitle());
        model.addAttribute("blogDescription", firstBlog.getDescription());
        model.addAttribute("blogTitle2", secondBlog.getTitle());
        model.addAttribute("blogDescription2", secondBlog.getDescription());
        model.addAttribute("blogTitle3", thirdBlog.getTitle());
        model.addAttribute("blogDescription3", thirdBlog.getDescription());
        model.addAttribute("firstBlog", firstBlog);
        model.addAttribute("secondBlog", secondBlog);
        model.addAttribute("thirdBlog", thirdBlog);
        return "index";
    }

    @GetMapping("/blog/{id}")
    public String blog(@PathVariable("id")Long id, Model model){
        Blog blog = blogMapper.selectById(id);
        model.addAttribute("blog", blog);
        return "blog";
    }

    //搜索
    @ResponseBody
    @GetMapping("/search")
    public R search(String keyword){
        //根据标题模糊搜索
        List<Blog> blogs = blogService.searchBlog(keyword.trim());
        return R.success().data("blogs",blogs);

    }
}
